//
//  KDNewsController.m
//  YuQingXiaoFang
//
//  Created by wangdongdong on 18/6/8.
//  Copyright © 2018年 KDTech. All rights reserved.
//

#import "KDNewsController.h"


#import "KDBaseListParam.h"

#import "KDTabBarController.h"

#import "KDNewsListParam.h"
#import "KDNewsRequestTool.h"
#import "KDNewsCellModel.h"
#import "KDNewsCell.h"

#import "KDNewsListResult.h"
#import "KDNewsCellModelFrame.h"
#import "KDHomeViewController.h"
#import "KDFocusRequestTool.h"
#import "KDFocusListParam.h"
#import "AlertTableView.h"
#import "KDAccountTool.h"
@interface KDNewsController ()<UITableViewDelegate,UITableViewDataSource,KDNewsCellDelegate>
/**
 *  所有主题数据的集合
 */
@property (nonatomic, strong) NSArray * themeArr;
/**  <#Description#> */
@property (nonatomic, strong) NSArray *infoArr;
/**  <#Description#> */
@property (nonatomic, weak) UITableView *currentTabV;
/**
 *  加载第几页
 */
@property (nonatomic, copy) NSString *page;
@property (nonatomic,strong) NSArray *modelFrames;
@end
static CGFloat const tableViewH = 75;

@implementation KDNewsController
#pragma mark - 懒加载区
- (NSString *)page
{
    if (!_page) {
        _page = @"1";
    }
    return _page;
}
- (NSArray *)infoArr
{
    if (!_infoArr) {
        _infoArr = [NSArray array];
    }
    return _infoArr;
}
#pragma mark -生命周期区
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavBar];
    [self setUpTableView];
     
}
#pragma mark - 板块布置区
- (void)setUpTableView
{
   CGFloat tableViewH1= homeSubControllerH;
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0  , 0, screenW, tableViewH1) style:UITableViewStylePlain];
    
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tag = 1000;
    tableView.tableFooterView = [UIView new];
    tableView.separatorColor = BackGroundColor;
    tableView.backgroundColor = BackGroundColor;
    tableView.rowHeight = tableViewH;
    [tableView setSeparatorColor:[UIColor grayColor]];
    
    //1.调整(iOS8以上)tableView边距(与上面第2步等效,二选一即可)
    if ([tableView respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        tableView.preservesSuperviewLayoutMargins = NO;
    }
    //2.调整(iOS8以上)view边距
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if (!iOS7) {
        tableView.estimatedRowHeight = tableViewH;
    }
    self.currentTabV = tableView;
    [self.view addSubview:tableView];
    //UINib *xib =[UINib nibWithNibName:@"KDNewsCell" bundle:nil] ;
    
    //[tableView registerNib:xib forCellReuseIdentifier:@"KDNewsCell"];
    
    
    
    
   
    tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadDetailData)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreDetailData)];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    // 设置footer
    self.currentTabV.footer = footer;
    [self.currentTabV.header beginRefreshing];
}
- (void)setupNavBar{
    //    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"collect_add"] style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClick)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"leftArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(leftItemClick)];
    
}
#pragma mark - 事件点击区
- (void)leftItemClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 网络请求区
- (void)loadDetailData{
    //WS(ws);
    KDNewsListParam *param = [[KDNewsListParam alloc]init];
    param.pageSize = @"20";
    self.page = @"1";
    param.pageNo = self.page;
    param.newsType=self.newsType;
    [KDNewsRequestTool getNewsListWithParam:param success:^(KDNewsListResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            self.infoArr = [KDNewsCellModel objectArrayWithKeyValuesArray:responseObejct.data];
            
            // 创建frame模型对象
            NSMutableArray *modelFrameArray = [NSMutableArray array];
            for (KDNewsCellModel *model in _infoArr) {
                KDNewsCellModelFrame *modelFrame = [[KDNewsCellModelFrame alloc] init];
                // 传递微博模型数据
                modelFrame.model = model;
                [modelFrameArray addObject:modelFrame];
            }
            
            // 赋值
            self.modelFrames = modelFrameArray;
            
            
            [self.currentTabV.header endRefreshing];
            [self.currentTabV reloadData];
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
            [self.currentTabV.header endRefreshing];
            [self.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
            [self.currentTabV.header endRefreshing];
        }
        
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
        [self.currentTabV.header endRefreshing];
        KDLog(@"%@",error);
        
    }];
}
- (void)loadMoreDetailData{
    
    KDNewsListParam *param = [[KDNewsListParam alloc]init];
    self.page = [NSString stringWithFormat:@"%ld", self.page.integerValue +1];
    param.pageNo = self.page;
    param.pageSize = @"20";
    param.newsType=self.newsType	;
    [KDNewsRequestTool getNewsListWithParam:param success:^(KDNewsListResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            
            NSArray *arr1 = [KDNewsCellModel objectArrayWithKeyValuesArray:responseObejct.data];
            if (arr1.count) {
                NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
                [arr addObjectsFromArray:arr1];
                self.infoArr = arr;
                [self.currentTabV.footer endRefreshing];
                [self.currentTabV reloadData];
            }else{
                [self.currentTabV.footer noticeNoMoreData];
            }
            
            
            [self.currentTabV reloadData];
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
            [self.currentTabV.footer endRefreshing];
            [self.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
            [self.currentTabV.footer endRefreshing];
        }
        
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
        [self.currentTabV.footer endRefreshing];
        KDLog(@"%@",error);
        
    }];
}
#pragma mark - 通知接收区
#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KDNewsCell *cell = [KDNewsCell cellWithTableView:tableView];
    //    KDLog(@"waimian%d", indexPath.row);
    cell.delegate = self;
    if (tableView == self.currentTabV)
    {
        cell.delegate = self;
        if (self.infoArr.count != 0)
        {
            cell.modelFrame = self.modelFrames[indexPath.row];
        }
        return cell;
    }else{
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    KDNewsCellModelFrame *modelFrame=self.modelFrames[indexPath.row];
    return modelFrame.cellHeight;
}

/**
 *  cell被点击了
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.currentTabV) {
        if (self.infoArr.count == 0) {
            return;
        }
        KDNewsCell *cell = (KDNewsCell *)[tableView cellForRowAtIndexPath:indexPath];
        NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
        [arr replaceObjectAtIndex:indexPath.row withObject:cell.modelFrame.model];
        self.infoArr = arr;
        //WS(ws);
        /**
        [self getNewsModelWithID:cell.model.newsId success:^(KDSubscribCellModel *model) {
            KDDetailSubscribController *singleCtrl = [[KDDetailSubscribController alloc]init];
            singleCtrl.delegate = ws;
            singleCtrl.model = model;
            
            
            [ws.navigationController pushViewController:singleCtrl animated:YES];
            
        }];
         */
        
    }
}

/**
 *  通过ID，请求获取一个本信息的所有细节
 *
 *  @param ID 信息ID
 */
/**
- (void)getNewsModelWithID:(NSString *)ID success:(void (^)(KDSubscribCellModel *model))success{
    
    KDMoveFavorParam *param = [[KDMoveFavorParam alloc]init];
    param.ID = ID;
    [SVProgressHUD showWithStatus:@"加载中…" maskType:SVProgressHUDMaskTypeGradient];
    [KDCollectRequestTool getNewsWithParam:param success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            KDSubscribCellModel * model= [KDSubscribCellModel objectWithKeyValues:responseObejct.data];
            [SVProgressHUD dismiss];
            if (model) {
                success(model);
            }else{
                [SVProgressHUD showInfoWithStatus:@"未查询到数据" maskType:SVProgressHUDMaskTypeGradient];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误!" maskType:SVProgressHUDMaskTypeGradient];
    }];
}
 
 */
/**
 *  添加关注
 *
 *  @param cell
 */

-(void)subscribCell:(KDNewsCell *)cell focusBtnClick:(UIButton *)focusBtn{
    __weak __typeof(self)weakSelf = self;
    NSIndexPath *index = [self.currentTabV indexPathForCell:cell];
    
    KDFocusListParam *param = [[KDFocusListParam alloc]init];
    KDAccount *account = [KDAccountTool account];
    param.apppersonid=[NSString stringWithFormat:@"%ld",account.userId];
    param.newsid=[NSString stringWithFormat:@"%ld",cell.modelFrame.model.id];
    param.newstype=[NSString stringWithFormat:@"%ld",cell.modelFrame.model.newsType];
    param.flag=@"1";
    [KDFocusRequestTool addFocusWithParam:param success:^(KDBaseResult *result) {
        if ([result.code isEqualToString:@"1"]) {
            AlertTableView *modelView = [[AlertTableView alloc] init];
            __weak typeof(AlertTableView) *weakModelView =modelView;
            [SVProgressHUD showSuccessWithStatus:result.msg maskType:SVProgressHUDMaskTypeGradient];
            //focusBtn.selected = YES;
            //KDNewsCellModel *model = weakSelf.infoArr[index.row];
            //model.attentStatus = 1;
            focusBtn.backgroundColor=[UIColor blueColor];
            focusBtn.enabled=NO;
            [weakModelView dismissSelfView];
        }else{
            [SVProgressHUD showErrorWithStatus:result.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

